#include <iostream>
#include <utility>
using namespace std;
template <typename T>
//实现自定义的Vector类接口
class Vector{
    public:
        Vector(){
            _start=_finish=_end_of_storage=nullptr;        
        }
        ~Vector(){
            while(_start!=_finish){
                --_finish;
                _alloc.destroy(_finish);
            }        
            if(_start==_finish){
                _alloc.deallocate(_start,capacity());
            }
        }
        void push_back(const T& value){
            size_t old_cap=capacity();
            size_t old_size=size();
            if(old_cap==old_size){
                reallocate();
            }
            //判断后，直接在_finish位置插入数据，然后_finish后移
            _alloc.construct(_finish,value);
            ++_finish;
        }
        void pop_back(){
            if(size()>0){
            --_finish;
            _alloc.destroy(_finish);
        }
        }
        int size(){
            return _finish-_start;
        }
        int capacity(){
            return _end_of_storage-_start;
        }
        void display(){
            T* start;
            while(start!=_finish){
                cout<<"11111"<<endl;
                cout<<*(start)<<" ";;
                ++start;
            }
        }
    private:
        void reallocate(){
        //先实现从0到1的扩容
        size_t old_cap=capacity();
        size_t new_cap=0;
        if(old_cap==0){
            new_cap=1;
        }else{
            //只要调用了扩容函数，不是给一个空间，就是直接空间翻倍
            new_cap=old_cap*2;
        }
        //扩容了就让新指针指向这个未初始化的内存空间
        T* new_start=_alloc.allocate(new_cap);
        //因为没有初始化，所有两个指针都指向开始位置
        T* new_finish=new_start;
        //把原来的元素一个一个给移动到新的内存空间
        for(T* p=_start;p!=_finish;++p){
            //因为new_finish一开始也指向起始位置,指针p和new_finish一起
            //移动，直到完全移动到新的内存地址
            _alloc.construct(new_finish,std::move(*p));
            ++new_finish;
            //直接调用析构函数
            _alloc.destroy(p);
        }
        //到这里就已经完全移动过去了，回收开始申请的空间
        if(_start!=nullptr){
            _alloc.deallocate(_start,old_cap);
        }
        _start=new_start;
        _finish=new_finish;
        _end_of_storage=_start+new_cap;
        }
    private:
        static std::allocator<T> _alloc;
        T* _start;
        T* _finish;
        T* _end_of_storage;
};
template <typename T> std::allocator<T> Vector<T>::_alloc;
void test(){
        Vector<int> vec;
        vec.push_back(10);
        vec.push_back(20);
        //vec.push_back(30);
        //vec.push_back(40);
       // vec.push_back(50);
       // vec.push_back(60);
       // vec.push_back(70);
       // vec.push_back(80);
       // vec.push_back(90);
       // vec.pop_back();
        vec.display();
}
int main(int argc, char * argv[]){
    test();
    return 0;
}

